package com.cdut.firstspringdemo.controller;

import com.cdut.firstspringdemo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

//Spring框架要求，只有被注解@Controller标注的类才是处理业务的类
@Controller
public class UserController {
    private static File userDir;//用来表示存放所有用户信息的目录

    static {
        userDir = new File("./users");
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    @RequestMapping("/deleteUser")
    public void delete(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理删除用户！！！！！！！！！");
        String Username = request.getParameter("Username");
        System.out.println("要删除的用户是"+Username);
        File file = new File(userDir,Username+".obj");
        file.delete();

        try {
            response.sendRedirect("/userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始建立动态表");
        /*
        读取users目录下所有obj文件并且反序列化然后得到所有User对象存入一个List集合
        生成HTML页面并将所有用户信息体现在其中并且发送给浏览器
         */
        List<User> userList = new ArrayList<>();
        //获取users目录下文件
        File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));
        //将每个文件反序列化得到User对象
        for (File file : subs){
            try(FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                ) {
                User user = (User)ois.readObject();
                userList.add(user);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println(userList);
        //
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"2\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("<td>操作</td>");
            pw.println("<tr>");

            for (User user : userList){
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                pw.println("<td><a href='/deleteUser?Username="+user.getUsername()+"'>删除</a></td>");
                pw.println("<tr>");
            }
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //@RequestMApping注解用于处理某个具体业务的方法，参数传入的字符串与对应页面中表单的action地址一样
    @RequestMapping("/regUser")
    public void register(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("helloworld!");
        /*
        获取注册页面register.html中表单提交的注册信息
        请求对象：HttpServletRequest，它表示浏览器本次提交上来的所有内容
        然后通过request对象获取表单中四个输入框的内容
         */
        String Username = request.getParameter("Username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        if (Username == null || Username.trim().isEmpty() ||
                password == null || password.trim().isEmpty() ||
                nickname == null || nickname.trim().isEmpty() ||
                ageStr == null || ageStr.trim().isEmpty() || !ageStr.matches("[0-9]+")) {
            //正则表达式，+表示前面的内容至少出现一次
            //相应错误页面
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        System.out.println(Username + "," + password + "," + "," + nickname + "," + ageStr);

        int age = Integer.parseInt(ageStr);
        User user = new User(Username, password, nickname, age);
        File file = new File(userDir, Username + ".obj");
        if (file.exists()) {
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos);) {
            oos.writeObject(user);
            //利用响应对象要求浏览器访问注册成功页面
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始登录");
        String Username = request.getParameter("Username");
        String password = request.getParameter("password");
        System.out.println(Username + "," + password + ",");
        if (Username == null || Username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        File file = new File(userDir, Username + ".obj");
        if (file.exists()) {
            try (FileInputStream fis = new FileInputStream(file);
                 ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();//读取回来的是注册用户信息
                //比较登录的密码和该用户的密码是否一致
                if (user.getPassword().equals(password)) {
                    //登录成功
                    response.sendRedirect("/login_success.html");
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        //独立处理登录失败
        try {
            response.sendRedirect("/login_fail.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
